package com.thl.filechooser

import android.app.Activity
import android.content.Context
import android.media.MediaScannerConnection
import android.text.TextUtils
import android.webkit.MimeTypeMap
import android.widget.SeekBar
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.SingleChoiceListener
import com.afollestad.materialdialogs.list.checkItem
import com.afollestad.materialdialogs.list.listItems
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import com.xzkj.sp.SpUtils
import java.io.File

/**
 * Description:
 * Data：$ $
 * Author: Allen
 */
object FileChooserListUtils {
    fun isSelectAll(fileInfoLIst: MutableList<FileInfo>, chooseType: String):Boolean{
        val fileSize = fileInfoLIst.filter { !it.isFolder }.size
        val fileCheckSize = fileInfoLIst.filter { !it.isFolder }.filter { it.isCheck }.size
        val folderSize = fileInfoLIst.filter { it.isFolder }.size
        val folderCheckSize = fileInfoLIst.filter { it.isFolder }.filter { it.isCheck }.size
        return when (chooseType) {
            FileInfo.FILE_TYPE_FILE -> {
                fileCheckSize==fileSize
            }
            FileInfo.FILE_TYPE_FOLDER -> {
                folderCheckSize == folderSize
            }
            else -> false
        }
    }

    fun getFileSize(fileInfoLIst: MutableList<FileInfo>):Int{
        return fileInfoLIst.filter { !it.isFolder }.size
    }
    fun getMaxByList(fileInfoLIst: MutableList<Int>): Int {
        return fileInfoLIst.maxOrNull() ?: return 0
    }
    fun getMinByList(fileInfoLIst: MutableList<Int>): Int {
        return  fileInfoLIst.minOrNull() ?: return 0
    }

    fun getFolderSize(fileInfoLIst: MutableList<FileInfo>):Int{
        return fileInfoLIst.filter { it.isFolder }.size
    }
    fun getListByAllKey(fileInfoLIst: MutableList<FileInfo>,key:String):List<FileInfo>{
        return fileInfoLIst.filter { it.fileName.contains(key) }
    }
    fun getListByFolderNameAz(fileInfoLIst: MutableList<FileInfo>):List<FileInfo>{
        return fileInfoLIst.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.fileName })
    }
    fun getListByFileNameAz(fileInfoLIst: MutableList<FileInfo>):List<FileInfo>{
        val sortedFileNames = fileInfoLIst.sortedWith(Comparator { o1, o2 ->
            val regex = Regex("[^a-zA-Z0-9]")
            val s1 = regex.replace(o1.fileName, "").toLowerCase().padStart(10, '0')
            val s2 = regex.replace(o2.fileName, "").toLowerCase().padStart(10, '0')
            s1.compareTo(s2)
        })
        return sortedFileNames
    }
    fun getListSortByIndex(context: Context,listIt: MutableList<FileInfo>):List<FileInfo>{
        val list = mutableListOf<FileInfo>()
        val listFolder = mutableListOf<FileInfo>()
        val listFile = mutableListOf<FileInfo>()
        listIt.forEach {
            if (it.isFolder){
                listFolder.add(it)
            }else{
                listFile.add(it)
            }
        }
        when (SpUtils.get(context, "file_chooser_sort_index", 0)) {
            0 -> {
                list.addAll(getListByFolderNameAz(listFolder))
                list.addAll(getListByFileNameAz(listFile))
            }
            1 -> {
                list.addAll(getListByFolderNameAz(listFolder).reversed())
                list.addAll(getListByFileNameAz(listFile).reversed())
            }
            2 -> {
                list.addAll(listFolder.sortedBy { File(it.filePath).lastModified() }.reversed())
                list.addAll(listFile.sortedBy { File(it.filePath).lastModified() }.reversed())
            }
            3 -> {
                list.addAll(listFolder.sortedBy { File(it.filePath).lastModified() })
                list.addAll(listFile.sortedBy { File(it.filePath).lastModified() })
            }
            4 -> {
                list.addAll(listFolder.sortedBy { File(it.filePath).length() }.reversed())
                list.addAll(listFile.sortedBy { File(it.filePath).length() }.reversed())
            }
            5 -> {
                list.addAll(listFolder.sortedBy { File(it.filePath).length() })
                list.addAll(listFile.sortedBy { File(it.filePath).length() })
            }
        }
        return list
    }


    fun getListSortMerge(context: Context,listFolder: MutableList<FileInfo>,listFile: MutableList<FileInfo>):List<FileInfo>{
        val list = mutableListOf<FileInfo>()
        when (SpUtils.get(context, "file_chooser_sort_index", 0)) {
            0 -> {
                list.addAll(getListByFolderNameAz(listFolder))
                list.addAll(getListByFileNameAz(listFile))
            }
            1 -> {
                list.addAll(getListByFolderNameAz(listFolder).reversed())
                list.addAll(getListByFileNameAz(listFile).reversed())
            }
            2 -> {
                list.addAll(listFolder.sortedBy { File(it.filePath).lastModified() }.reversed())
                list.addAll(listFile.sortedBy { File(it.filePath).lastModified() }.reversed())
            }
            3 -> {
                list.addAll(listFolder.sortedBy { File(it.filePath).lastModified() })
                list.addAll(listFile.sortedBy { File(it.filePath).lastModified() })
            }
            4 -> {
                list.addAll(listFolder.sortedBy { File(it.filePath).length() }.reversed())
                list.addAll(listFile.sortedBy { File(it.filePath).length() }.reversed())
            }
            5 -> {
                list.addAll(listFolder.sortedBy { File(it.filePath).length() })
                list.addAll(listFile.sortedBy { File(it.filePath).length() })
            }
        }
        return list
    }

    fun openFileSelect(
        context: Activity,
        title: String?,
        chooseCount: Int,
        listener: FileChooser.FileChoosenListener
    ) {
        val fileChooser = FileChooser(
            context,
            listener)
        fileChooser.setBackIconRes(R.drawable.back_white)
        fileChooser.setTitle(title)
//        fileChooser.setCurrentPath(path)
        fileChooser.setDoneText("确定")
        fileChooser.setThemeColor(R.color.themeColor)
        fileChooser.isShowHideFile = true
        fileChooser.chooseType = FileInfo.FILE_TYPE_FILE
        fileChooser.showFile(true) //是否显示文件
        fileChooser.chooseCount = chooseCount
        fileChooser.open()
    }

    fun showListDialog(
        context: Context,
        title: String = "",
        items: List<String>,
        listCall: DialogListCall
    ) {
        MaterialDialog(context).show {
            if (!TextUtils.isEmpty(title)) {
                title(text = title)
            }
            listItems(items = items) { _, index, text ->
                listCall.listCall(index, text.toString())
            }
        }
    }
    fun showSingleCheckListDialog(
        context: Context,
        sortIndex: Int,
        items: List<String>,
        listCall: DialogListCall
    ) {
        MaterialDialog(context).show {
            listItemsSingleChoice(
                items = items,
                selection = object : SingleChoiceListener {
                    override fun invoke(
                        dialog: MaterialDialog,
                        index: Int,
                        text: CharSequence
                    ) {
                        listCall.listCall(index,text.toString())
                    }
                })
            checkItem(sortIndex)
        }
    }

    fun scanFileToMediaStore(filePath: String, context: Context) {
        MediaScannerConnection.scanFile(
            context,
            arrayOf(filePath),
            arrayOf(MimeTypeMap.getSingleton().getMimeTypeFromExtension(filePath.substring(filePath.lastIndexOf('.') + 1))),
            null
        )
    }
    fun scrollSeekbar(seekBar: SeekBar, recyclerView: RecyclerView) {
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 根据滑动的进度来更新 RecyclerView 的滚动位置
                val maxScroll = recyclerView.computeVerticalScrollRange() - recyclerView.height
                val scrollPosition = (progress / 100f * maxScroll).toInt()
                recyclerView.scrollTo(0, scrollPosition)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 用户开始滑动滑块时的操作
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 用户停止滑动滑块时的操作
            }
        })
    }

    interface DialogListCall {
        fun listCall(index: Int, content: String?)
    }
}